package com.lengyu.vxminiprogram.vx.miniprogram.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lengyu.vxminiprogram.common.ConstData;
import com.lengyu.vxminiprogram.common.HttpResultDto;
import com.lengyu.vxminiprogram.convert.IUserConverter;
import com.lengyu.vxminiprogram.entity.User;
import com.lengyu.vxminiprogram.security.jwt.JwtUtils;
import com.lengyu.vxminiprogram.security.rest.dto.JwtUser;
import com.lengyu.vxminiprogram.service.IUserService;
import com.lengyu.vxminiprogram.vx.miniprogram.service.IVxApiService;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu
 * @since 2023-01-18
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private IVxApiService vxApiService;

    @Autowired
    private IUserService userService;


    /**
     * 登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 进行登录凭证校验
     * @param code
     * @return
     */
    @PostMapping(value="/auth")
    public HttpResultDto<JSONObject> doAuth(String code){
        JSONObject resultJson =vxApiService.code2Session(code);
        if(resultJson.containsKey("openid")){
            String openId = resultJson.getString("openid");
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("vx_open_id",openId);
            User user =   userService.getOne(queryWrapper,false);
            if(user == null){
                String defaultName = "勇士"+System.currentTimeMillis();
                User user1 = new User();
                user1.setId(openId);
                user1.setUsername(defaultName);
                user1.setVxOpenId(openId);
                user1.setPassword(DigestUtils.md5Hex(ConstData.PASSWORD_SALT +  "ggdsmedar"));
                user1.setVxNickName(defaultName);
                user1.setVxAvatar("https://wow.shuzhipeixian.com:12812/download/avatar/default.jpeg");
                userService.saveOrUpdate(user1);

                resultJson.put("vxNickName",defaultName);
                resultJson.put("userName",defaultName);
                resultJson.put("avatar","https://wow.shuzhipeixian.com:12812/download/avatar/default.jpeg");
                JwtUser jwtUser = new JwtUser();
                jwtUser.setId(user1.getId());
                jwtUser.setUsername(user1.getUsername());

                String token = JwtUtils.GenToken(jwtUser,user1.getId(),false);
                resultJson.put("lengyu_token",token);
                resultJson.put("openId",openId);
                resultJson.put("userId",user1.getId());
            }
            else{
                resultJson.put("nickName",user.getVxNickName());
                resultJson.put("avatar", user.getVxAvatar());
                JwtUser jwtUser = new JwtUser();
                jwtUser.setId(user.getId());
                jwtUser.setUsername(user.getUsername());

                String token = JwtUtils.GenToken(jwtUser,user.getId(),false);
                resultJson.put("lengyu_token",token);
                resultJson.put("openId",openId);
                resultJson.put("userId",user.getId());
            }



        }

        return HttpResultDto.success(resultJson);
    }

    @PostMapping(value="/test")
    public HttpResultDto<String> test(String test){
        logger.info("收到上传日志：" + test);

        return HttpResultDto.success();
    }

//    @PreAuthorize("hasPermission('*', 'user_edit')")
//    @PostMapping(value="/update")
//    public HttpResultDto<String> update(@RequestBody UserWithPermissionViewDto UserWithPermissionViewDto){
//        User user = userPermiToUserConverter.dtoToEntity(UserWithPermissionViewDto);
//        List<String> roleCodeList = UserWithPermissionViewDto.getRoles();
//        QueryWrapper queryWrapper = new QueryWrapper();
//        List<RoleUserRelation> roleUserRelationList = new ArrayList<>();
//        if(roleCodeList != null && roleCodeList.size() > 0){
//            queryWrapper.in("code",roleCodeList);
//            List<Role> roleList = roleService.list(queryWrapper);
//            if(roleList != null && roleList.size() > 0){
//                roleList.forEach(i->{
//                    RoleUserRelation roleUserRelation = new RoleUserRelation();
//                    roleUserRelation.setUserId(user.getId());
//                    roleUserRelation.setRoleId(i.getId());
//                    roleUserRelation.initInsert();
//                    roleUserRelationList.add(roleUserRelation);
//                });
//            }
//        }
//
//        if(StringUtils.isNotBlank(user.getId())){
//            //更新用户信息时候不更新密码
//            user.setPassword(null);
//            userService.updateById(user);
//            queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_id",user.getId());
//            roleUserRelationService.remove(queryWrapper);
//            roleUserRelationService.saveBatch(roleUserRelationList);
//        }
//        else{
//            return HttpResultDto.failed("用户ID不存在无法更新");
//        }
//
//        return HttpResultDto.success();
//    }

//    @PreAuthorize("hasPermission('*', 'user_edit')")
//    @PostMapping(value="/delete")
//    public HttpResultDto<String> delete(@RequestBody JSONObject json){
//        List<String> userIds = Arrays.asList(json.getString("ids").split(","));
//        UpdateWrapper updateWrapper = new UpdateWrapper();
//        updateWrapper.set("delete_flag",true);
//        updateWrapper.in("id",userIds);
//        userService.update(updateWrapper);
//        return HttpResultDto.success();
//    }
//
//    //参数1(/user/page)指明了访问该接口需要的url，参数2®指明了访问该接口需要的权限。
//    @PreAuthorize("hasPermission('*', 'user_read')")
//    @PostMapping(value="/page")
//    public HttpResultDto<Page<UserWithPermissionViewDto>> page(@RequestBody BasePageParamDto pageParamDto){
//        QueryWrapper queryWrapper = new QueryWrapper();
//        if(pageParamDto.getParamMapObj() != null){
//            for(String key:pageParamDto.getParamMapObj().keySet()){
//                if(StringUtils.isNotBlank(String.valueOf(pageParamDto.getParamMapObj().get(key)))){
//                    queryWrapper.like(key,pageParamDto.getParamMapObj().get(key));
//                }
//            }
//        }
//        Page<UserWithPermissionView> entityPage = userWithPermissionViewService.page(new Page<>(pageParamDto.getPageIndex(), pageParamDto.getPageSize()),queryWrapper);
//        Page<UserWithPermissionViewDto> dtoPage = userWithPermissionViewConverter.pageEntityToDto(entityPage);
//        return HttpResultDto.success(dtoPage);
//    }
//
//    @PreAuthorize("hasPermission('*', 'user_read')")
//    @GetMapping(value="/detail")
//    public HttpResultDto<UserDto> detail(String id){
//        User user = userService.getById(id);
//        UserDto userDto = userConverter.entityToDto(user);
//        return HttpResultDto.success(userDto);
//    }
//
//    @GetMapping(value="/user-info")
//    public HttpResultDto<UserWithPermissionViewDto> getUserInfo(){
//        String userId = AuthUtil.getCurrentJwtUser().getId();
//        UserWithPermissionView user = userWithPermissionViewService.getById(userId);
//        UserWithPermissionViewDto dto = userWithPermissionViewConverter.entityToDto(user);
//        return HttpResultDto.success(dto);
//    }
//
//    @GetMapping(value="/listForSelect")
//    public HttpResultDto<List<UserDto>> listForSelect(){
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.select("id","username");
//        List<User> entityList = userService.list(queryWrapper);
//        List<UserDto> entityDtoList = userConverter.listEntityToDto(entityList);
//        return HttpResultDto.success(entityDtoList);
//    }
}
